package cn.eng.basic.exception;

import cn.eng.basic.commonenum.ErrorCode;
import cn.eng.basic.utils.AjaxResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice//对所有加了@RequestMapping注解的类 进行增强
public class GlobalExceptionHandle {
    @ExceptionHandler(BusinessException.class)//捕获指定类型抛出的异常信息
    public AjaxResult handleException(BusinessException e){
        e.printStackTrace();
        ErrorCode errorCode = ErrorCode.getByCode(e.getMessage());
        return new AjaxResult()
                .setCode(errorCode.getCode())
                .setSuccess(false)
                .setMsg(errorCode.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)//捕获指定类型抛出的异常信息
    public AjaxResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        return new AjaxResult()
                .setCode("400")
                .setSuccess(false)
                .setMsg("参数异常");
    }

    /**
     * 捕获 非业务异常的信息
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e){
        e.printStackTrace();
        return new AjaxResult()
                .setCode(ErrorCode.SYSTEM_ERROR.getCode())
                .setSuccess(false)
                .setMsg(ErrorCode.SYSTEM_ERROR.getMessage());
    }
}
